/**
 * @description Axios instance function
 */

import axios from 'axios'
import { notification } from 'antd'
import { messages } from '../i18n/i18nProvider'
// import { browserHistory } from 'react-router-dom'

const projectID = '5b375760ac15607c8cb8419d'
const instance = axios.create({
  baseURL:`https://www.easy-mock.com/mock/${projectID}`,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// Intercept request
instance.interceptors.request.use(
  config => {
    // The login interface does not require token information
    if (config.url !== '/login') {
      let token = localStorage.getItem('authenticationToken')
      token
        ? (config.headers.common['X-Subject-Token'] = token)
        : window.parent.postMessage({ status: 403 }, '*')
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// Intercept response
instance.interceptors.response.use(
  response => {
    response.headers &&
      response.headers['x-subject-token'] &&
      response.headers['x-subject-token'] !== 'None' &&
      localStorage.setItem(
        'authenticationToken',
        response.headers['x-subject-token']
      )

    return response.config.url === '/login'
      ? response.headers['x-subject-token'] !== 'None'
        ? response.headers['x-subject-token']
        : null
      : response.data
  },
  err => {
    if (err && err.response && err.response.status) {
      switch (err.response.status) {
        case 403:
          process.env.NODE_ENV === 'development' &&
            (localStorage.clear(), sessionStorage.clear())
          return Promise.reject(err)
        case 401:
          notification.warning({
            message:
              messages.i18n_common_401_title + messages.i18n_common_colon,
            description: messages.i18n_common_401_description
          })
          return Promise.reject(err)
        default:
          notification.error({
            message: messages.i18n_common_error,
            description: messages.i18n_common_service_exception
          })
          return Promise.reject(err)
      }
    }

    notification.error({
      message: messages.i18n_common_error,
      description:
        err.response && err.response.data && err.response.data.message
          ? err.response.data.message
          : messages.i18n_common_service_exception
    })
    return Promise.reject(err)
  }
)

export default instance
